<template>
  <!-- 在线咨询 来源报表 -->
  <div class="landing" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" :query="query" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" v-on:click.stop="search(1)">{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="accs">
                  <span class="access">{{$t('report.imAccessId')}}：</span>
                  <el-select size="mini" v-model.trim="selectedAccessIdList" multiple filterable :placeholder="$t('report.searchByName')">
                    <el-option
                      v-for="item in accessIdOptions"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value">
                    </el-option>
                  </el-select>
                </div>
                <div class="accs">
                  <span class="access1">url：</span>
                  <el-input v-model.trim="fuzzyURL" :placeholder="$t('report.UrlBlurSearch')"></el-input>
                </div>
                <div class="accs">
                  <el-checkbox v-model="positiveSessionCount">{{$t('report.ProductDialogueData')}}</el-checkbox>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="$t('report.imReportSourceLeadingTop10')"></affix>
    </div>
    <div :id="id">
      <table class="pank">
        <tr>
          <td>{{$t('report.imReportSourceFromRank')}}</td>
          <td>{{$t('report.fromUrl')}}</td>
          <td>{{$t('report.totalSessionCount')}}</td>
        </tr>
        <tr v-for="(item, index) in top" :key="index">
          <td :style="[index < 3 ? {color: item.color} : '']">{{ index+1 }}</td>
          <td v-html="item._id"></td>
          <td>
            <span class="number">{{ item.sessionCount }} </span>
            <div class="line" :style="{width: item.width, background: item.color}"></div>
          </td>
        </tr>
      </table>
      <div style="padding: 0 30px 0 20px"><affix :label="$t('report.imReportSourceLeading')"></affix></div>
      <div class="tab">
        <div class="export">
          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportExcel"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportExcel"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
          <el-button class="primary_btn fr pdf" @click.stop="exportReportTask">{{$t('customer.exportTaskList')}}</el-button>
        </div>
        <div class="deploy">
          <div class="search-pagination">
            <pagination
                :small="paginationRecord.small"
                :currentPage="paginationRecord.currentPage"
                :count="countRecord"
                :num="paginationRecord.num"
                @turnPage="turnPageRecord"
                :totalPage="totalPageRecord"
                >
            </pagination>
          </div>
          <span class="tex fr">{{$t('report.totalRecord', {countNum: countNum})}}</span>
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                1. {{$t('report.allConSationNumber')}}<br>
                2. {{$t('report.imPersonSessionNum')}}<br>
                3. {{$t('report.imRobotSessionNum')}}<br>
                4. {{$t('report.imSeatInviteNum')}}<br>
                5. {{$t('report.initiatingNumber')}}<br>
                6. {{$t('report.imLostSessionCount')}}<br>
                7. {{$t('report.imTurnToPerson')}}<br>
                8. {{$t('report.imFineSessionNum1')}}<br>
                9. {{$t('report.imBadSessionNum1')}}<br>
                10. {{$t('report.imKindSessionNum1')}}<br>
                11. {{$t('report.imTurnCustomNum')}}<br>
                12. {{$t('report.imEveryClickNum')}}<br>
                13. {{$t('report.imEveryAskNum')}}<br>
                14. {{$t('report.visitorCount')}}<br>
                <span v-if="isTip">
                  15. {{$t('report.imReportLeaveNum')}}<br>
                  16. {{$t('report.imChanceTurnRate')}}<br>
                  17. {{$t('report.imLeaveRate')}}<br>
                  18. {{$t('report.imWebChanceNum')}}<br>
                  19. {{$t('report.imWebvisitNum')}}<br>
                  20. {{$t('report.activeClaimRobotSessionCount')}}<br>
                </span>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="tableData" :config="headOptions.Config" :sum="totalData"> </report-table>
      </div>
    </div>
    <export-count-down @close="close" :isDialogVisible="isDialogVisible"></export-count-down>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../../ui-modules/unfold/index.vue'
  import dateTime from '../../base/datetime.vue'
  import reportTable from '../../base/reportTable.vue'
  import exportCountDown from '../../base/exportCountDown.vue'
  import { deepClone, optionTimeTypeCheck } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, searchTime, checkTime, exportNum } from '@/utils/reportUtils.js'
  import Pagination from '@/components/public-modules/card/Pagination'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'

  export default {
    name: 'landing',
    data () {
      return {
        isDialogVisible: false, // 是否展示倒计时
        positiveSessionCount: false, // 产生对话数的数据
        fuzzyURL: '', // url搜索绑定值
        isFold: false, // 是否展示搜索条件
        selectedAccessIdList: [], // 接入号绑定值
        accessIdOptions: [], // 接入号渲染数据
        id: 'im_report_session_landingPageUrl', // 查询id
        title: this.$t('report.imReportSourceFromUrl'),
        query: {}, // 查询条件
        dialogVisible: false, // 导出pdf弹窗开关
        loading: false, // 查询时展示加载的开关
        colorClass: 'colo',
        top10Colors: ['#985fac', '#ee596f', '#f48c4d', '#7acdd1', '#7acdd1', '#7acdd1', '#7acdd1', '#7acdd1', '#7acdd1', '#7acdd1'], // top10颜色数组
        headOptions: { Config: [], data: [] }, // 表头数据
        serverData: [], // 原始查询table数据
        paginationRecord: { // 翻页组件传入的数据
          currentPage: 1,
          small: 'small',
          num: 20
        },
        countRecord: 0, // 当前页
        totalPageRecord: 1, // 共有多少页
        countNum: 0, // 共有多少条记录
        top: [] // top10数据
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable,
      Pagination,
      exportCountDown
    },
    computed: {
      // 是否展示网站相关数据
      isTip () {
        if (!this.headOptions.Config || this.headOptions.Config.length === 0) {
          return false
        }
        let bool = false
        this.headOptions.Config.map(item => {
          if (item.name === 'userVisitCount' && item.show) {
            bool = true
          }
        })
        return bool
      },
      tableData () {
        return this.getTableData(this.serverData)
      },
      totalData () {
        return this.getTotalData(this.serverData, this.headOptions)
      }
    },
    methods: {
      // 关闭导出任务提示弹窗
      close (data) {
        if (data === 'export') {
          this.exportReportTask()
        }
        this.isDialogVisible = false
      },
      // 路由跳转到导出任务列表
      exportReportTask () {
        this.$router.push({
          path: '/index/report/report_export',
          query: {
            isExport: true
          }
        })
      },
      // 处理table数据
      getTableData (serverData) {
        if (!serverData || serverData.length === 0) {
          return []
        }

        let data = deepClone(serverData)

        data.forEach(item => {
          item.landingPageUrl = `<a href=${item.landingPageUrl} target="_blank">${item.landingPageUrl}</a>`
        })

        return data
      },
      // 计算table合计
      getTotalData (serverData, headOptions) {
        if (!serverData || serverData.length === 0) {
          return [{fromUrl: this.$t('report.total')}]
        }
        let headerConfig = headOptions.Config || []
        let datas = serverData
        let total = {
          landingPageUrl: this.$t('report.total')
        }

        for (let i = 0; i < headerConfig.length; i++) {
          for (let j = 0; j < datas.length; j++) {
            if (!isNaN(datas[j][headerConfig[i].name])) {
              if ((headerConfig[i].name in total) === false) {
                total[headerConfig[i].name] = 0
              }
              total[headerConfig[i].name] += datas[j][headerConfig[i].name]
            }
          }
        }
        total.userConsultRate = total.userVisitCount > 0 ? Math.round((total.userConsultCount / total.userVisitCount) * 100) : 0
        total.userConsultRate = total.userConsultRate > 100 ? 100 : total.userConsultRate
        total.userLeaveRate = total.userVisitCount > 0 ? Math.round((total.userLeaveCount / total.userVisitCount) * 100) : 0
        total.url = ''
        return [total]
      },
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 查询数据的条件
      getSearchQueryData (page, limit, isExport) {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id, seoSource: this.seoSource },
          page: page || 1,
          limit: limit,
          positiveSessionCount: false
        }
        if (!isExport) {
          this.paginationRecord.currentPage = page
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        query.fuzzyURL = this.fuzzyURL
        query.positiveSessionCount = this.positiveSessionCount
        data.query = Object.assign({}, data.query, query)
        return data
      },
      // 查询方法
      search (page) {
        var queryData = this.getSearchQueryData(page, 20)

        if (!queryData) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryImSessionFromReport', queryData).then((res) => {
          // 表头
          this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
          this.serverData = deepClone(res.data) || this.serverData
          this.page = queryData.page
          let count = res.count || 0
          if (count) {
            this.countNum = count
            this.totalPageRecord = Math.ceil(count / 20)
            this.countRecord = count / 2
          } else {
            this.countNum = 0
            this.totalPageRecord = 1
            this.countRecord = 1
          }

          if (!page || page === 1) {
            let data = deepClone(this.serverData)
            data = data.slice(0, 10)

            this.top = data.map((item, index) => ({
              _id: `<a href=${item.landingPageUrl} target="_blank">${item.landingPageUrl}</a>`,
              width: data[0].sessionCount > 0 ? Math.round(80 * item.sessionCount / data[0].sessionCount) + '%' : 0,
              color: this.top10Colors[index],
              sessionCount: item.sessionCount
            }))
          }
          this.loading = false
        })
      },
      exportExcel () {
        var queryData = this.getSearchQueryData(1, exportNum.searchNum, true)
        if (!queryData) {
          return
        }
        if (this.countNum > exportNum.maxExportNum) {
          this.$message.warning(this.$t('report.imReportMoreDateTipErro'))
          return
        }
        // if (this.countNum > exportNum.endExportNum) {
        //   let data = queryData.query
        //   this.$store.dispatch('addReportExportTask', data).then((response) => {
        //     console.log(response, 6666)
        //   })
        //   this.isDialogVisible = true
        //   return
        // }
        this.loading = true
        this.$store.dispatch('queryImSessionFromReport', queryData).then((res) => {
          this.loading = false
          if (res.count > exportNum.maxExportNum) {
            this.$message.warning(this.$t('report.imReportMoreDateTipErro'))
            return
          }
          this.exportXlsx(res)
          // if (this.$store.getters.exportFromFront) {
          //   this.exportXlsx(res)
          // } else if (this.$store.getters.exportFromEnd) {
          //   this.exportXls()
          // }
        })
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx (res) {
        var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
        var serverData = deepClone(res.data) || this.serverData

        var tableData = this.getTableData(serverData, headOptions).map(d => {
          var reg = /<\/?.+?\/?>/g
          if (d && d.landingPageUrl && d.landingPageUrl.replace) {
            d.landingPageUrl = d.landingPageUrl.replace(reg, '')
          }
          return d
        })

        var headers = headOptionsToXlsxHeaders(headOptions.Config)
        if (tableData && tableData.length) {
          var sum = this.getTotalData(serverData, headOptions)
          tableData = tableData.concat(sum)
        }

        var dh = XlsxUtil.getDownloadHelper(headers, tableData)
        var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
        dh.download(this.$t('report.imReportSourceFrom') + timeStamp)
      },
      // 导出表格数据执行的方法(前端)
      // exportXlsx () {
      //   var queryData = this.getSearchQueryData(1, 100000000, true)

      //   if (!queryData) {
      //     return
      //   }

      //   this.loading = true
      //   this.$store.dispatch('queryImSessionFromReport', queryData).then((res) => {
      //     this.loading = false

      //     var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
      //     var serverData = deepClone(res.data) || this.serverData

      //     var tableData = this.getTableData(serverData, headOptions).map(d => {
      //       var reg = /<\/?.+?\/?>/g
      //       if (d && d.landingPageUrl && d.landingPageUrl.replace) {
      //         d.landingPageUrl = d.landingPageUrl.replace(reg, '')
      //       }
      //       return d
      //     })

      //     var headers = headOptionsToXlsxHeaders(headOptions.Config)
      //     if (tableData && tableData.length) {
      //       var sum = this.getTotalData(serverData, headOptions)
      //       tableData = tableData.concat(sum)
      //     }

      //     var dh = XlsxUtil.getDownloadHelper(headers, tableData)
      //     var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
      //     dh.download(this.$t('report.imReportSourceFrom') + timeStamp)
      //   })
      // },
      // 翻页查询方法 参数当前请求页数
      turnPageRecord (pageNum) {
        this.paginationRecord.currentPage = pageNum
        this.search(pageNum)
      },
      // 导出表格数据执行的方法(后端)
      exportXls () {
        let data = {
          Method: 'exportImSourceAnalyse',
          Query: {
            reportType: this.id,
            includeSubordinate: this.includeSubordinate,
            user: this.$store.state.session.user._id
          }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        query.fuzzyURL = this.fuzzyURL
        query.positiveSessionCount = this.positiveSessionCount
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImSessionFromReport', data)
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      },
      // 确认导出pdf执行的方法
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.sourcePageReport') + searchTime(this.query), id: this.id})
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', { type: 'accessIds' }).then(accessIds => {
        this.accessIdOptions = accessIds.map(accessId => ({ label: `${accessId.name}[${accessId.platform}]`, name: accessId.name, platform: accessId.platform, value: accessId._id }))
      })
      this.$nextTick(() => {
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .landing
    .accs
      margin 14px 0 0px 0px
      .access
        margin-right 10px
      .access1
        margin-right 30px
      .el-select
      .el-input
        width 600px
    .tab
      margin-top 0
      .deploy
        .tip
          margin-left 0
        .search-pagination
          float right
          line-height 23px
        .tex
          display inline-block
          margin 2px 10px 0 0
          height 26px
          line-height 26px
        .tex:hover
          color $cf-gray1
    .pank
      width 100%
      padding 20px
      margin-left 20px
      tr
        td
          line-height 24px
          &:nth-child(1)
            width 10%
          &:nth-child(2)
            width 50%
          &:nth-child(3)
            width 40%
      .line
        display inline-block
        margin-bottom 4px
        height 5px
      .number
        display inline-block
        width 60px
</style>
